package com.atguigu.yygh.hosp.controller.api;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.hosp.bean.Result;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.hosp.utils.MD5;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.HospitalSet;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author luoyin
 * @Date 21:19 2022/9/26
 **/
@RestController
@RequestMapping("/api/hosp")
@Api("医院信息设置")
public class ApiHospitalController {

    @Autowired
    HospitalService hospitalService;

    @Autowired
    HospitalSetService hospitalSetService;

    @PostMapping("/saveHospital")
    @ApiOperation(value = "上传医院")
    public Result<Hospital> saveHospital(Hospital hospital, Long timestamp, String sign){

        //对比sign 是否一致
        String signKey = hospitalSetService.getSignKeyByHoscode(hospital.getHoscode());
        if (StringUtils.isEmpty(signKey)){
            throw new YyghException(201,"signKey为空");
        }
        //签名校验
        String signKeyMD5 = MD5.encrypt(signKey);
        if(!sign.equals(signKeyMD5)){
            throw new YyghException(201,"校验失败");
        }
        String logoData = hospital.getLogoData();
        hospital.setLogoData(logoData.replaceAll(" ","+"));
        hospitalService.saveHospital(hospital);
        return Result.ok();
    }
    
    @PostMapping("/hospital/show")
    public Result<Hospital> show(@RequestParam Map<String ,String> paramMap){
        //校验key
        String sign = paramMap.get("sign");
        String hoscode = paramMap.get("hoscode");
        String timestamp = paramMap.get("timestamp");
        String signKey = hospitalSetService.getSignKeyByHoscode(hoscode);
        //签名校验
        String strSign = hoscode + "|" + timestamp + "|" + signKey ;
        String signKeyMD5 = MD5.encrypt(strSign);
        if(!sign.equals(signKeyMD5)){
            throw new YyghException(201,"校验失败");
        }
        //查询信息
        Hospital hospital = hospitalService.findByHoscode(hoscode);
        if (hospital == null){
            throw new YyghException(201,"该医院信息不存在!");
        }

        return Result.ok(hospital);
    }
}
